package com.news.servlet.admin;

import com.news.model.User;
import com.news.service.UserService;
import com.news.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/userManage")
public class UserManageServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private static final int PAGE_SIZE = 10;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取当前页码
            int currentPage = 1;
            String pageStr = request.getParameter("page");
            if (pageStr != null && !pageStr.isEmpty()) {
                currentPage = Integer.parseInt(pageStr);
            }

            // 获取搜索关键词
            String keyword = request.getParameter("keyword");

            // ��取用户总数和总页数
            int totalUsers = userService.getUserCount(keyword);
            int totalPages = (totalUsers + PAGE_SIZE - 1) / PAGE_SIZE;

            // 获取当前页的用户列表
            List<User> userList = userService.getUsersByPage(currentPage, PAGE_SIZE, keyword);

            // 设置属性
            request.setAttribute("userList", userList);
            request.setAttribute("currentPage", currentPage);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("keyword", keyword);

            // 转发到用户管理页面
            request.getRequestDispatcher("/admin/user_manage.jsp").forward(request, response);
        } catch (Exception e) {
            request.getSession().setAttribute("message", "获取用户列表失败：" + e.getMessage());
            request.getRequestDispatcher("/admin/user_manage.jsp").forward(request, response);
        }
    }
} 